import { SocketContainer } from '@/hooks/useSocket'
import { history, useLocation, useParams } from 'umi'
import Store from './store'
import { observer, useLocalObservable } from 'mobx-react'
import { getCookie, getLocalStorage, getSessionStorage } from '@/storage'
import { useEffect } from 'react'
import { kingWs } from '@/servers/kingUrl'
import wx from 'weixin-webview-jssdk'

export default observer((props: any) => {
    const store = useLocalObservable(() => Store)
    const { userInfo, setData } = store
    const { uid } = userInfo

    /** useParams 无法获取到参数兼容写法 */
    const location = useLocation()
    const { pathname } = location
    const href = pathname.split('/')
    const id = href[href.length - 1]

    /** 白名单 */
    const whiteUrl = ['/auction/result/']
    const isWhiteUrl = !!whiteUrl.filter(item => window.location.href.indexOf(item) > -1).length

    useEffect(() => {
        const userData = getLocalStorage('USER_DATA')
        userData && setData('userInfo', userData)
    }, [])

    return uid ? (
        <div>
            {isWhiteUrl ? (
                props.children
            ) : (
                <SocketContainer.Provider
                    initialState={{
                        url: kingWs,
                        time: 10000,
                        params: {
                            channel: 'auction-game',
                            token: getCookie('TOKEN'),
                            user_id: uid,
                            role: 'client',
                            auction_record_id: id,
                        },
                        init: ({ send, onMessage }) => {
                            /** 状态流转 */
                            const step_flow = ({ data }: any) => {
                                const { goto, lot_obj, user_balance } = data || {}
                                let url: string = ''
                                console.log(goto)
                                switch (goto) {
                                    case 'submit':
                                        url = `/auction/statistics/${id}`
                                        break
                                    case 'info':
                                        url = `/auction/explain/${id}`
                                        break
                                    case 'game':
                                        url = `/auction/game/${id}`
                                        setData('lot_obj', { ...lot_obj, user_balance })
                                        break
                                    case 'statistic':
                                        url = `/auction/result/${id}`
                                        break
                                    default:
                                        break
                                }
                                const curHref = window.location.href
                                if (curHref.indexOf(url) < 0 && url) {
                                    history.replace(url)
                                }
                            }
                            onMessage('step_flow', step_flow)
                            onMessage('connect', ({ data }: any) => {
                                const { lot_arr, goto, lot_obj, user_balance, is_submit, bidding_result, is_pass, form_statistic_arr } = data
                                console.log(data)
                                let url: string = ''
                                switch (goto) {
                                    case 'form':
                                        if (is_submit === '1') {
                                            url = `/auction/statistics/${id}`
                                        } else {
                                            url = `/auction/${id}`
                                        }
                                        setData(
                                            'lot_arr',
                                            lot_arr?.map((item: any) => ({ ...item, value: item?.estimate_price || 0 })),
                                        )
                                        break
                                    case 'submit':
                                        url = `/auction/statistics/${id}`
                                        setData(
                                            'lot_arr',
                                            form_statistic_arr?.map((item: any) => ({ ...item, value: item?.statistic?.estimate_price || 0 })),
                                        )
                                        break
                                    case 'info':
                                        url = `/auction/explain/${id}`
                                        break
                                    case 'game':
                                        url = `/auction/game/${id}`
                                        setData('binding_info', { binding_result: bidding_result, is_pass })
                                        setData('lot_obj', { ...lot_obj, user_balance })
                                        break
                                    case 'statistic':
                                        url = `/auction/result/${id}`
                                        break
                                    default:
                                        break
                                }
                                const curHref = window.location.href
                                if (curHref.indexOf(url) < 0 && url) {
                                    history.replace(url)
                                }
                            })
                            onMessage('error', ({ data }: any) => {
                                const { code } = data || {}
                                /** 特殊 code */
                                switch (code) {
                                    case 405:
                                        if (window.__wxjs_environment === 'miniprogram') {
                                            wx.miniProgram.navigateBack()
                                        } else {
                                            history.goBack()
                                            // history.replace('/training')
                                        }
                                        break
                                    default:
                                        break
                                }
                            })

                            /** 建立连接 */
                            send('connect')
                        },
                    }}
                >
                    {props.children}
                </SocketContainer.Provider>
            )}
        </div>
    ) : null
})
